<template>
  <div class="query">
    <el-input
      placeholder="请输入角色名称"
      style="width: 200px; margin-right: 13px"
      v-model="roleName"
      clearable
    />
    <el-button @click="handleQuery">查询</el-button>
    <el-button type="primary" @click="handleAddRole" v-has="'sys-role-add'">新增</el-button>
  </div>

  <div class="table">
    <el-table
      :data="roleList.rows"
      border
      style="width: 100%"
      v-loading="tableLoading"
    >
      <el-table-column prop="role_name" label="角色名称" align="center" />
      <el-table-column prop="desc" label="备注" align="center" />
      <el-table-column prop="created_time" label="创建时间" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            @click.prevent="handleEditor(scope.row)"
            v-has="'sys-role-edit'"
          >
            编辑
          </el-button>

          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="red"
            title="确定删除此角色?"
            @confirm="handledeleteRow(scope.row)"
          >
            <template #reference>
              <el-button type="text" size="small" v-has="'sys-role-del'"> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      small
      layout="prev, pager, next"
      :total="total"
      @current-change="handleCurrentChange"
      hide-on-single-page
    ></el-pagination>
  </div>

  <el-dialog
    v-model="dialogVisible"
    :title="isAdd ? '新增' : '编辑'"
    width="50%"
    :before-close="handleClose"
  >
    <div>
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="ruleForm"
        label-width="80px"
      >
        <div class="login-input">
          <el-form-item prop="role_name" label="角色名称">
            <el-input
              placeholder="角色名称"
              v-model="ruleForm.role_name"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注" prop="desc">
            <el-input placeholder="备注" v-model="ruleForm.desc" clearable />
          </el-form-item>
          <el-form-item label="权限">
            <el-tree
              ref="treeRef"
              :data="roleMenu"
              default-expand-all
              :props="defaultProps"
              show-checkbox
              :highlight-current="true"
              :expand-on-click-node="true"
              node-key="id"
              :default-checked-keys="selectedArr"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleDetermine(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import { ref, reactive, onMounted, unref } from "vue";
import type { ElForm } from "element-plus";
import {
  addUserRole,
  roleQueryRoleByPage,
  queryRolePermissions,
  queryAllPermissions,
  roleDel,
  roleEdit,
} from "../../api/user";

type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance>();

onMounted(() => {
  handelGetRole();
  queryAllPermissions({}).then((res: any) => {
    if (res.code === 200) {
      roleMenu.value = res.data;
    }
  });
});

// 列表总条数
const total = ref<number>(0);

const treeRef = ref<any>(null);
const tableLoading = ref<boolean>(false);

// 查询
const handleQuery = () => {
  page.value = 1;
  handelGetRole();
};

// 分页
const handleCurrentChange = (currentPageNum: number) => {
  page.value = currentPageNum;
  handelGetRole();
};

// 新增 or 编辑
const isAdd = ref<boolean>(true);

const handleAddRole = () => {
  dialogVisible.value = true;
  isAdd.value = true;
};
// 编辑获取对应菜单
const selectedArr = ref([]);

// 获取所有节点id
const getTreeId = (data: any[] = [], arr: any[] = []) => {
  for (let item of data) {
    arr.push(item.id);
    if (item.subs && item.subs.length) getTreeId(item.subs, arr);
  }
  return arr;
};

// 列表编辑按钮
const handleEditor = (row: any) => {
  editId.value = row.id;
  ruleForm.role_name = row.role_name;
  ruleForm.desc = row.desc;
  queryRolePermissions({ role_id: row.id }).then((res: any) => {
    if (res.code === 200) {
      console.log(res);
      selectedArr.value = res.data;
    }
  });
  isAdd.value = false;
  dialogVisible.value = true;
};

// 角色列表
const roleList = ref<any>([]);
const roleName = ref("");
const page = ref(1);

// 获取角色列表
const handelGetRole = () => {
  const params = {
    page: page.value,
    limit: 10,
    role_name: roleName.value,
  };
  tableLoading.value = true;
  roleQueryRoleByPage(params).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.count;
      tableLoading.value = false;
      roleList.value = res.data;
    }
  });
};

// tree配置
const defaultProps = {
  children: "subs",
  label: "title",
};

// 用户选中菜单
const roleSelectedMenu = ref([]);

//tree 操作事件
const handleCheckChange = (data: any, val: any) => {
  roleSelectedMenu.value = val.checkedNodes;
  console.log(roleSelectedMenu.value);
};

// 新增角色窗口
const dialogVisible = ref(false);

// 删除角色
const handledeleteRow = (row: any) => {
  roleDel({ id: row.id }).then((res: any) => {
    if (res.code === 200) {
      handelGetRole();
      ElMessage({
        message: "删除角色成功",
        type: "success",
      });
    }
  });
};

const ruleForm = reactive({
  role_name: "",
  desc: "",
});

// 列出所有菜单
const roleMenu = ref([]);

const editId = ref<number>(-1);
// 表单重制
const resetFormData = ref(null);

// 触发新增 or 编辑角色btn确定
const handleDetermine = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      selectedArr.value = [];
      const { role_name, desc } = ruleForm;
      const params:any = {
        role_name,
        desc,
        state: 1,
        permission_ids: treeRef.value
          .getCheckedNodes(false, true)
          .map((item: any) => item.id)
          .join(),
      };
      if (!isAdd.value){
        params.id = editId.value;
      }
      const data: any = isAdd.value
        ? await addUserRole(params)
        : await roleEdit(params);
      if (data.code === 200) {
        dialogVisible.value = false;
        ElMessage({
          message: `${isAdd.value ? "创建" : "编辑"}角色成功`,
          type: "success",
        });
        page.value = 1;
        total.value = 0;
        ruleFormRef.value?.resetFields();
        treeRef.value.setCheckedKeys([]);
        handelGetRole();
      }
    } else {
      return false;
    }
  });
  // dialogVisible.value = false;
};

// 关闭角色窗口
const handleClose = () => {
  const form = unref(ruleFormRef);
  form?.resetFields();
  // ruleFormRef.value.resetFields();
  treeRef.value.setCheckedKeys([]);
  dialogVisible.value = false;
};

// 正则校验
const rules = reactive({
  role_name: [
    {
      required: true,
      message: "请输入角色名称",
      trigger: "blur",
    },
  ],
  desc: [],
});
</script>

<style scoped></style>
